package log

import (
	"os"
	"path/filepath"

	"gitee.com/botaoshow/yuanxin/web/common/conf"
	"github.com/sirupsen/logrus"
	"gopkg.in/natefinch/lumberjack.v2"
)

var Logger *logrus.Logger

// InitDevLogger 初始化开发环境日志配置
func InitDevLogger() *logrus.Logger {
	logger := logrus.New()
	logger.SetLevel(logrus.DebugLevel)
	logger.SetFormatter(&logrus.TextFormatter{
		FullTimestamp: true,
		ForceColors:   true,
	})
	logger.SetOutput(os.Stdout)

	logger.Info("Development logger initialized")
	Logger = logger
	return logger
}

// InitProdLogger 初始化生产环境日志配置
func InitProdLogger() *logrus.Logger {
	logCfg := conf.AppConfig.Log
	logDir := "./logs"
	if logCfg.Path != "" {
		logDir = logCfg.Path
	}

	// 确保日志目录存在
	if _, err := os.Stat(logDir); os.IsNotExist(err) {
		err := os.MkdirAll(logDir, 0755)
		if err != nil {
			return nil
		}
	}

	// 配置日志轮转
	infoWriter := &lumberjack.Logger{
		Filename:   filepath.Join(logDir, "app.log"),
		MaxSize:    100,
		MaxAge:     7,
		MaxBackups: 10,
		Compress:   true,
	}

	logger := logrus.New()
	logger.SetLevel(logrus.InfoLevel)
	logger.SetFormatter(&logrus.JSONFormatter{
		TimestampFormat: "2006-01-02T15:04:05.000Z07:00",
	})
	logger.SetOutput(infoWriter)

	logger.Info("Production logger initialized with log rotation")
	Logger = logger
	return logger
}
